package com.atguigu.gmall.pms.service.impl;

import com.atguigu.gmall.pms.entity.*;

import com.atguigu.gmall.pms.entity.vo.SkuVo;
import com.atguigu.gmall.pms.entity.vo.SpuAttValueVo;
import com.atguigu.gmall.pms.entity.vo.SpuVo;
import com.atguigu.gmall.pms.feign.GmallSmsClient;
import com.atguigu.gmall.pms.mapper.*;

import com.atguigu.gmall.pms.service.SpuAttrValueService;
import com.atguigu.gmall.sms.vo.SkuSaleVo;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.common.bean.PageResultVo;
import com.atguigu.gmall.common.bean.PageParamVo;

import com.atguigu.gmall.pms.service.SpuService;


@Service("spuService")
public class SpuServiceImpl extends ServiceImpl<SpuMapper, SpuEntity> implements SpuService {
    @Autowired
    SpuAttrValueService spuAttrValueService;

    @Autowired
    SpuDescMapper spuDescMapper;

    @Autowired
    SkuMapper skuMapper;

    @Autowired
    SkuAttrValueMapper skuAttrValueMapper;

    @Autowired
    SkuImagesMapper skuImagesMapper;

    @Autowired
    GmallSmsClient gmallSmsClient;

    @Autowired
    RabbitTemplate rabbitTemplate;
    @Override
    public PageResultVo queryPage(PageParamVo paramVo) {
        IPage<SpuEntity> page = this.page(
                paramVo.getPage(),
                new QueryWrapper<SpuEntity>()
        );

        return new PageResultVo(page);
    }

    @Override
    public PageResultVo getPmsList(long categoryId, PageParamVo pageParamVo) {
        QueryWrapper<SpuEntity> queryWrapper = new QueryWrapper<>();
       //如果不等于0则需要分类查询
        if (categoryId!=0){
            queryWrapper.eq("category_id",categoryId);
        }
        String key = pageParamVo.getKey();
        if (!StringUtils.isBlank(key)){
            queryWrapper.and(t->t.eq("id",key).or().like("name",key));
        }
        IPage<SpuEntity> page = this.page(
                pageParamVo.getPage(),
                queryWrapper
        );
        return new PageResultVo(page);
    }

    @GlobalTransactional
    @Override
    public void saveSpuVo(SpuVo spu) {
        //1、保存spu的相关信息
         //1.1保存spu主要信息
        Long spuId = saveSpuInfo(spu);
        // 1.2保存spu基本信息
        saveSpuBasic(spu, spuId);
        // 1.3保存spu描述信息
        saveSpuDesc(spu, spuId);
        //2、保存sku的相关信息
        saveSkuInfo(spu, spuId);
        //保存完发送消息到MQ
        sendMsgToMQ(spuId,"save");
        //发送消息从mq通知购物车服务同步最新价格信息


    }

    private void saveSkuInfo(SpuVo spu, Long spuId) {
        List<SkuVo> skus = spu.getSkus();
        if (skus!=null){
        skus.forEach(t->{
            SkuEntity skuEntity = new SkuEntity();
            BeanUtils.copyProperties(t,skuEntity);
            skuEntity.setCategoryId(spu.getCategoryId());//通过spu获取cid
            skuEntity.setBrandId(spu.getBrandId());//通过spu获取brand_id
            skuEntity.setSpuId(spuId);
            List<String> images = t.getImages();
            if (images!=null){
                skuEntity.setDefaultImage(t.getDefaultImage()!=null? t.getDefaultImage():images.get(0));
            }
            skuMapper.insert(skuEntity);
            Long skuId = skuEntity.getId();
            //2.2保存sku的属性相关值的信息
            List<SkuAttrValueEntity> saleAttrs = t.getSaleAttrs();
            if (saleAttrs!=null){
            saleAttrs.forEach(sku_att_val->{
                sku_att_val.setSkuId(skuId);
                    skuAttrValueMapper.insert(sku_att_val);
            });
            }
            //2.3保存sku的基本信息
            images.forEach(image->{
            SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
            skuImagesEntity.setSkuId(skuId);
            skuImagesEntity.setUrl(image);
            skuImagesEntity.setDefaultStatus(image==skuEntity.getDefaultImage()?1:0);
            skuImagesMapper.insert(skuImagesEntity);
            });
        //3、保存营销相关信息
            SkuSaleVo skuSaleVo = new SkuSaleVo();
            BeanUtils.copyProperties(t,skuSaleVo);
            skuSaleVo.setSkuId(skuId);
            gmallSmsClient.saveSkuSaleInfo(skuSaleVo);
        });
        }
    }

    private void saveSpuDesc(SpuVo spu, Long spuId) {
        List<String> spuImages = spu.getSpuImages();
        if (spuImages!=null){
        SpuDescEntity spuDescEntity = new SpuDescEntity();
        spuDescEntity.setSpuId(spuId);
        spuDescEntity.setDecript(StringUtils.join(spuImages,","));
        spuDescMapper.insert(spuDescEntity);
        }
    }

    private void saveSpuBasic(SpuVo spu, Long spuId) {
        List<SpuAttValueVo> baseAttrs = spu.getBaseAttrs();
        if (baseAttrs!=null){
        List<SpuAttrValueEntity> collect = baseAttrs.stream().map(t -> {
            SpuAttrValueEntity spuAttrValueEntity = new SpuAttrValueEntity();
            BeanUtils.copyProperties(t, spuAttrValueEntity);
            spuAttrValueEntity.setSpuId(spuId);
            return spuAttrValueEntity;
        }).collect(Collectors.toList());
        spuAttrValueService.saveBatch(collect);
        }
    }

    private Long saveSpuInfo(SpuVo spu) {
        spu.setCreateTime(new Date());
        spu.setUpdateTime(spu.getCreateTime());
        this.save(spu);
        return spu.getId();
    }

    private void sendMsgToMQ(Long id,String type){
        try {
            this.rabbitTemplate
                    .convertAndSend("PMS_SPU_EXCHANGE","item."+type,id);
        } catch (AmqpException e) {
//            logger.error("{}商品消息发送异常，商品id：{}", type, id, e);
            e.printStackTrace();
        }
    }
}